package com.tngames.angrytunisian.game.core.entity;

import static playn.core.PlayN.assets;
import static playn.core.PlayN.graphics;
import playn.core.Image;
import playn.core.ImageLayer;
import playn.core.PlayN;
import playn.core.ResourceCallback;

/**
 * Based on the forplay-peaphysics example (Copyright 2011 The ForPlay Authors),
 * which is licensed under the Apache License, Version 2.0.
 */
public abstract class Entity {
	protected ImageLayer layer;
	float x, y, angle;

	public Entity(final EntityEngine entityEngine, float px, float py,
			float pangle) {
		this.x = px;
		this.y = py;
		this.angle = pangle;
		layer = graphics().createImageLayer(getImage());
		initPreLoad(entityEngine);
		getImage().addCallback(new ResourceCallback<Image>() {
			@Override
			public void done(Image image) {
				// since the image is loaded, we can use its width and height
				layer.setWidth(image.width());
				layer.setHeight(image.height());
				layer.setOrigin(image.width() / 2f, image.height() / 2f);
				layer.setScale(getWidth() / image.width(),
						getHeight() / image.height());
				layer.setTranslation(x, y);
				layer.setRotation(angle);
				initPostLoad(entityEngine);
			}

			@Override
			public void error(Throwable err) {
				PlayN.log().error("Error loading image: " + err.getMessage());
			}
		});

		entityEngine.add(this);
	}

	/**
	 * Perform pre-image load initialization (e.g., attaching to entityEngine
	 * layers).
	 * 
	 * @param entityEngine
	 */
	public abstract void initPreLoad(final EntityEngine entityEngine);

	/**
	 * Perform post-image load initialization (e.g., attaching to entityEngine
	 * layers).
	 * 
	 * @param entityEngine
	 */
	public abstract void initPostLoad(final EntityEngine entityEngine);

	public void update(float delta) {
	}

	public ImageLayer getLayer() {
		return layer;
	}

	public void setPos(float x, float y) {
		layer.setTranslation(x, y);
	}

	public float getPosX() {
		return layer.transform().tx();
	}

	public float getPosY() {
		return layer.transform().ty();
	}

	public void setAngle(float a) {
		layer.setRotation(a);
	}

	public abstract float getWidth();

	public abstract float getHeight();

	public abstract Image getImage();

	protected static Image loadImage(String name) {
		return assets().getImage(name);
	}
}
